﻿
using System;
using System.Globalization;
using System.Threading;

namespace NoNameGoServer.Client.Commands {
    public abstract class Command {
        public class CompletedArgs { }
        public delegate void CompletedDelegate(Command sender, CompletedArgs args);
        public event CompletedDelegate Completed;
        private readonly EventWaitHandle _completedEventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

        public EventWaitHandle CompletedEventWaitHandle {
            get { return _completedEventWaitHandle; }
        }

        public virtual void ProcessReceivedLine(NNGSClient nngsClient, string line, out bool processed) {
            if (IsPromptLine(line)) {
                FireCompleted(this, new CompletedArgs());
                processed = true;
                return;
            }
            processed = false;
        }

        public abstract void Execute(NNGSClient nngsClient);

        public virtual void SendComplete(NNGSClient nngsClient, int sendCount, object state) {
        }

        protected void FireCompleted(Command sender, CompletedArgs args) {
            _completedEventWaitHandle.Set();
            if (Completed != null) {
                Completed(sender, args);
            }
        }

        protected bool IsPromptLine(string line) {
            return line.StartsWith(
                "#>", true, CultureInfo.InvariantCulture) ||
                line.StartsWith("1 5", true, CultureInfo.InvariantCulture) ||
                line.StartsWith("1 6", true, CultureInfo.InvariantCulture) ||
				line.StartsWith("1 7", true, CultureInfo.InvariantCulture);
        }

        public void MarkCompleted() {
            FireCompleted(this, new CompletedArgs());
        }
    }
}
